package com.cloud.salon.client.business.service.impl;

import com.cloud.salon.common.base.response.Res;
import com.cloud.salon.common.base.util.ValueUtil;
import com.cloud.salon.common.base.vo.business.ItemLineVO;
import com.cloud.salon.common.crud.service.impl.CRUDServiceImpl;
import com.cloud.salon.client.business.repository.ItemRepository;
import com.cloud.salon.client.business.service.ItemService;
import com.cloud.salon.common.base.entity.business.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description 项目Service实现类
 * @Author wolf--LZH
 * @CreateDate 2019/4/10 0010 下午 1:30
 */
@Service
public class ItemServiceImpl extends CRUDServiceImpl<Item, ItemRepository> implements ItemService {

	@Autowired
	private ItemRepository repository;

	public Res<List<Item>> findByIdList(List<Integer> ids) {
		List<Item> items = new ArrayList<>();

		List<Integer> idList = new ArrayList<>();
		for (Integer id: ids) {
			// 若已经包含该id,则先查询已有集合
			if (idList.contains(id)) {
				items.addAll(repository.findByIdIn(idList));
				idList.clear();
			}
			// 把当前id添加到集合中去
			idList.add(id);
		}
		items.addAll(repository.findByIdIn(idList));
		if (ids.size() != items.size())
			return new Res(-3, "查询失败,部分数据不存在");
		return new Res(0, "查找成功", items);
	}

	public Res<List<ItemLineVO>> findByRecord(Integer recordId) {
		List<Map<String, String>> itemLines = repository.findByRecord(recordId);

		List<ItemLineVO> itemLineVOS = transformToVO(itemLines);

		if(itemLineVOS != null)
			return new Res(0, "查找成功", itemLineVOS);
		else
			return new Res(-3, "查找失败");
	}

	private List<ItemLineVO> transformToVO(List<Map<String, String>> itemLines) {
		List<ItemLineVO> itemLineVOS = new ArrayList<>();

		for (Map<String, String> itemLine: itemLines) {
			try {
				Integer id = Integer.valueOf(itemLine.get("id"));
				String name = (String)itemLine.get("name");
				String description = (String)itemLine.get("description");
				String price = ValueUtil.valueOf(2, Double.valueOf(itemLine.get("price")));
				Integer number = Integer.valueOf(itemLine.get("number"));

				itemLineVOS.add(new ItemLineVO(id, name, description, price, number));
			} catch (Exception e) {
				return null;
			}
		}

		return itemLineVOS;
	}
}
